package cn.jietuo.nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2021/2/26
 * @description: NIO引入多路复用器
 */
public class NioSelectorServer {


    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        // 设置非阻塞
        serverSocketChannel.configureBlocking(false);
        // 打开selector处理channel，即创建epoll
        Selector selector = Selector.open();
        // 把serversocketchannel注册到selector上,并且selector对客户端accept连接操作感兴趣
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务器启动成功");
        while(true){
            // 阻塞等待需要处理的事件发生
            selector.select();
            // 获取selector中注册的全部事件的SelectionKey实例
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                // 如果是OP_ACCEPT事件，则进行获取事件注册
                if (key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel clientSocketChannel = server.accept();
                    clientSocketChannel.configureBlocking(false);
                    // 继续注册读事件
                    clientSocketChannel.register(selector,SelectionKey.OP_READ);
                    System.out.println("客户端连接成功");
                }else if(key.isReadable()){
                    // 是可读事件
                    SocketChannel clientSocketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    int read = clientSocketChannel.read(byteBuffer);
                    // 如果有数据，打印
                    if (read > 0){
                        System.out.println("接受到消息：" + new String(byteBuffer.array()));
                    }else if(read == -1){
                        System.out.println("客户端断开连接");
                        clientSocketChannel.close();
                    }
                }
                iterator.remove();
            }
        }
    }
}
